<template>
  <div>
      <el-card>
      <div slot="header">
        <my-breadcrumb>个人设置</my-breadcrumb>
      </div>

      <el-row>
        <el-col :span="16">
            <!-- 表单 -->
            <el-form label-width="80px">
              <el-form-item label="编号">
                <span>{{userInfo.id}}</span>
              </el-form-item>
               <el-form-item label="手机">
            <span>{{userInfo.mobile}}</span>
              </el-form-item>
               <el-form-item label="名称">
                <el-input v-model="userInfo.name" />
              </el-form-item>
               <el-form-item label="简介">
                <el-input type="textarea" v-model="userInfo.intro"
                :row="3"></el-input>
              </el-form-item>
               <el-form-item label="邮箱">
                <el-input v-model="userInfo.email" />
              </el-form-item>
              <el-form-item>
                <el-button @click="hSave">保存设置</el-button>
              </el-form-item>
            </el-form>
        </el-col>
        <el-col :span="8">
            <el-upload
              class="avatar-uploader"
              action=""
              :http-request="hUpload"
              :headers="headers"
              name="image"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload">
                <!-- 当上传成功之后，imageUrl就会有值，此时做预览
                  给img设置了src后，显示图片内容的过程是异步的 ---- 并不是设了src后就可以立即看到图片的

                  问：你怎么知道图片已经完成了加载？
                -->
                <el-image v-if="userInfo.photo" :src="userInfo.photo" class="avatar"/>
                <!-- 没有上传之前，这里是一个大大的 + -->
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<script>
export default {
  data () {
    return {
      imageUrl: '',
      // imageUrl: '../assets/default.png', // 图片按钮
      headers: {
        Authorization: `Bearer ${localStorage.getItem('tokenStr')}`// 设置请求头token
      },
      userInfo: { // 配置数据项
        name: '',
        intro: '',
        email: '',
        mobile: '',
        photo: ''
      }
    }
  },
  created () {
    // 订阅时间,这个事件会从个人中心修改成功之后发出来
    this.$eventBus.$on('userinfo-update', obj => {
      console.log('收到了用户信息更新的消息', obj)
      // obj.newPhoto && (this.user.photo = obj.newPhoto)
      if (obj.newPhoto) {
        this.user.photo = obj.newPhoto
      }
      obj.newName && (this.user.name = obj.newName)
    })
    this.$axios({
      method: 'get',
      url: '/mp/v1_0/user/profile'
      // headers: {
      //   Authorization: `Bearer ${localStorage.getItem('tokenStr')}`
      // }
    }).then(res => {
      console.log(res)
      this.user = res.data.data
    }).catch(err => {
      console.log(err)
      // 没有登陆,请先登陆
      this.$message.error('请先登录')
      localStorage.removeItem('tokenStr')
      this.$roueter.push('/login')
    })
    this.loadUserInfo()
  },
  methods: {
    async loadUserInfo () {
      try {
        const res = await this.$axios({
          method: 'get',
          url: '/mp/v1_0/user/profile'
        })
        const {
          email,
          id,
          intro,
          mobile,
          name,
          photo
        } = res.data.data
        this.userInfo = {
          email,
          id,
          intro,
          mobile,
          name,
          photo
        }
        this.imageUrl = photo
      } catch (err) {
        console.log(err)
      }
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      // file.size 单位是字节
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async doSave () {
      const { name, intro, email } = this.userInfo
      try {
        const res = await this.$axios({
          method: 'patch',
          url: '/mp/v1_0/user/profile',
          data: {
            name,
            intro,
            email
          }
        })
        console.log(res)
        // 1.提示
        this.$message.success('修改成功')
        // 2.通知layout去更新名字
        this.$eventBus.$emit('userinfo-update', {
          newName: name
        })
      } catch (err) {
        console.log(err)
        this.$message.error('修改失败')
      }
    },
    // hSuccess (res) {
    //   // res中保存着本次上传操作成功后，后端接口返回的数值
    //   // 1. 预览效果
    //   this.uploadImageUrl = res.data.url
    //   // console.log('文件上传成功', res, file)
    //   this.$message.success('上传成功')
    // },
    // 自定义表单信息验证
    // 如果验证成功,返回true,否则返回false
    validate () {
      const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z]{2,4}$/
      const { name, intro, email } = this.userInfo
      if (name === '' || intro === '' || email === '') {
        this.$message.error('用户名, 简介, 邮箱 不能为空')
        return false
      }
      // 验证邮箱格式
      if (!regEmail.test(email)) {
        this.$message.error('邮箱格式不对')
        return false
      }
      return true
    },
    hSave () {
      // 1.验证
      if (!this.validate()) {
        return
      }
      // 2.保存
      this.doSave()
    },
    // el-upload组件中的http-request
    // 在弹出框中,点击确认时,它会自动调用
    async hUpload (config) {
      console.log('上传中...', config.file)
      try {
        // 原生的ajax上传文件
        // formData
        // 由于上传的参数是文件,必须要用formData来组装参数
        const fd = new FormData()
        // 向fd中添加一个参数
        fd.append('photo', config.file)
        const res = await this.$axios({
          url: '/mp/v1_0/user/photo',
          method: 'patch',
          data: fd
        })
        this.$message.success('头像更新成功')
        // 本地更新
        console.log(config)
        console.log(this.res.data.data.photo)
        this.imageUrl = res.data.data.photo
        // 通知layout去更新头像
        this.$eventBus.$emit('userinfo-update', { newPhoto: this.imageUrl })
      } catch (err) {
        this.$message.error('头像更新失败')
        console.log(err)
      }
    }
  }
}
</script>

<style lang="less" scoped>

.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #ddd;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
